<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Models\Coupon;
use App\Models\CouponType;
use App\Models\UserCoupon;
use App\Models\Brand;
use App\Models\Category;
use App\Models\Goods;
use App\Http\Requests\Admin\AdminCoupon\CouponStoreRequest;
use App\Exceptions\Admin\CouponException;
use DB;

class CouponController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request, Category $category)
    {
        //品牌数组
        $brandInfo = Brand::all();
        $brandArr = ['0'=>'选择品牌'];
        foreach ($brandInfo as $key => $value) {
            $brandArr[$value->brand_id] = $value->brand_name;
        }//end foreach()

        $search = ['name'=>'', 'type'=>'0'];
        $typeArr = [1=>'全场通用', 2=>'商品', 3=>'分类', 4=>'店铺', 5=>'品牌'];

        $query = Coupon::orderBy('created_at', 'desc');
        $name = @$request->name;
        if (@$name) {
            $query = $query->where('name', $name);
            $search['name'] = $name;
        }//end if()

        $type = @$request->type;
        if (@$type) {
            $query = $query->where('type', $type);
            $search['type'] = $type;
        }//end if()

        $coupons = $query->paginate(10);

        return view('admin.coupon.index', compact('coupons', 'search', 'typeArr','category', 'brandArr'));
    }//end func index()

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Coupon $coupon, Category $category, Request $request)
    {
        $typeArr = [1=>'全场通用', 2=>'商品', 3=>'分类', 4=>'店铺', 5=>'品牌'];
        $coupons = '';


        $search = ['name'=>'', 'type'=>'0'];

        //品牌数组
        $brandInfo = Brand::all();
        $brandArr = ['0'=>'选择品牌'];
        foreach ($brandInfo as $key => $value) {
            $brandArr[$value->brand_id] = $value->brand_name;
        }//end foreach()

        return view('admin.coupon.create', compact('coupon', 'search', 'typeArr','category', 'brandArr'));
    }//end func create()

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(CouponStoreRequest $couponStoreRequest)
    {

        $use_id_str = @$couponStoreRequest->use_id_str;
        if ($couponStoreRequest->type!=1 && empty($use_id_str)) {
            throw new CouponException("类型的值不能为空");
        }//end if()

        DB::beginTransaction();//开启事务,开始批量操作

        try {

            $coupon = Coupon::create($couponStoreRequest->all());
            if (empty($coupon)) {
                throw new CouponException('优惠券添加失败');
            }//end if()

            $coupon_id = $coupon->id;

            if ($couponStoreRequest->type!=1 && !empty($use_id_str)) {

                $use_id_arr = explode(',', $use_id_str);
                if (!empty($use_id_arr)) {
                    foreach ($use_id_arr as $key => $value) {

                        $use_id = $value;
                        $coupon_type = CouponType::create(['coupon_id'=>$coupon_id, 'use_id'=>$use_id]);

                        if (empty($coupon_type)) {
                            throw new CouponException('优惠券类型值添加失败');
                        }//end if()
                    }//end foreach()
                }//end if()
            }//end if()

        } catch (Exception $e) {

            DB::rollback();
            throw new CouponException('优惠券添加失败');
        }

        DB::commit();

        return Redirect('admin/coupon');

    }//end func store()

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id, Category $category, Request $request)
    {
        $back_url = '';
        if($request->back_url){
            $back_url = $request->back_url;
        }//end if()

        $typeArr = [1=>'全场通用', 2=>'商品', 3=>'分类', 4=>'店铺', 5=>'品牌'];
        $coupons = Coupon::findOrNew($id);
        $coupon_id = $coupons->id;
        //echo '<BR>coupon id:'.$coupon_id;
        $coupon_type = CouponType::where('coupon_id', $coupon_id)->get();
        $use_id_str = '';
        foreach ($coupon_type as $key => $value) {

            $use_id = $value->use_id;

            if ($key==0) {

                $use_id_str = $use_id;
            }else{

                $use_id_str .= ','.$use_id;
            }//end if()

        }//end foreach()

        //品牌数组
        $brandInfo = Brand::all();
        $brandArr = ['0'=>'选择品牌'];
        foreach ($brandInfo as $key => $value) {
            $brandArr[$value->brand_id] = $value->brand_name;
        }//end foreach()

        $goods = [];
        if ($coupons->type==2) {

            $coupon_types = CouponType::where('coupon_id', $id)->get();

            //根据商品id查找商品是否存在
            foreach ($coupon_types as $key => $value) {
                $goods_id = $value->use_id;
                $goodsInfo = Goods::find($goods_id);
                if ($goodsInfo) {
                    $goods[$key] = $goodsInfo->toArray();
                }
            }//end foreach()

        }//end ifx
        return view('admin.coupon.edit', compact('coupons', 'typeArr', 'back_url', 'goods', 'category', 'brandArr', 'use_id_str'));
    }//end func edit()

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(CouponStoreRequest $couponStoreRequest, $coupon_id)
    {//dd($couponStoreRequest->all());

        $use_id_str = @$couponStoreRequest->use_id_str;
        if ($couponStoreRequest->type!=1 && empty($use_id_str)) {
            throw new CouponException("类型的值不能为空");
        }//end if()

        DB::beginTransaction();//开启事务,开始批量操作

        try {

            $coupon=Coupon::findOrNew($coupon_id);
            $coupon = $coupon->update($couponStoreRequest->all());

            if (empty($coupon)) {
                throw new CouponException('优惠券编辑失败');
            }//end if()

            $coupon_type = CouponType::where('coupon_id', $coupon_id)->delete();

            if ($couponStoreRequest->type!=1 && !empty($use_id_str)) {

                $use_id_arr = explode(',', $use_id_str);

                foreach ($use_id_arr as $key => $value) {
                    $use_id = $value;
                    $coupon_type = CouponType::create(['coupon_id'=>$coupon_id, 'use_id'=>$use_id]);
                    if (empty($coupon_type)) {
                        throw new CouponException('优惠券类型值添加失败');
                    }//end if()
                }//end foreach()
            }//end if()

        } catch (Exception $e) {

            DB::rollback();
            throw new CouponException('优惠券编辑失败');
        }

        DB::commit();

        $pre_url = @$couponStoreRequest->pre_url;

        if($pre_url){

            return Redirect($pre_url);
        }else{

            return Redirect('admin/coupon');
        }//end if()

    }//end func update

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($coupon_id, Request $request)
    {
        $return = ['status'=>1, 'message'=>'', 'data'=>''];

        $amount = UserCoupon::where('coupon_id', $coupon_id)->count();

        if (empty($amount) || $amount==0) {

            $coupon=Coupon::findOrNew($coupon_id);
            $coupon->delete();

        }else{

            $return['status'] = 0;
            $return['message'] = '删除失败，该优惠券已有用户领取';
            return $return;
        }//end if()

        $pre_url = @$request->pre_url;

        if($pre_url){

            $return['data'] = $pre_url;
        }else{

            $return['data'] = 'admin/coupon';
        }//end if()
        return $return;

    }//end func destory()

}
